package com.jiujichaoshi.oauth.server.security.sms;

import com.jiujichaoshi.oauth.server.security.DefaultVariableName;
import com.jiujichaoshi.oauth.server.security.ExtendAuthenticationToken;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.util.ObjectUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Description: 处理grant_type为sms的请求，生成认证信息，进行认证，返回TOKEN
 *
 * @author YangLong [410357434@163.com]
 * @version V1.0
 * @date 2021/2/4
 */
@SuppressWarnings("deprecation")
public class SmsTokenGranter extends AbstractTokenGranter {
    private final AuthenticationManager authenticationManager;
    /**
     * 手机号参数名
     **/
    private String mobileParameter = DefaultVariableName.SMS_LOGIN_NAME;
    /**
     * 验证码参数名
     **/
    private String smsCodeParameter = DefaultVariableName.SMS_LOGIN_CAPTCHA;

    public SmsTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, AuthenticationManager authenticationManager) {
        super(tokenServices, clientDetailsService, requestFactory, DefaultVariableName.SMS_GRANT_TYPE);
        this.authenticationManager = authenticationManager;
    }

    public SmsTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, AuthenticationManager authenticationManager, String mobileParameter, String smsCodeParameter) {
        super(tokenServices, clientDetailsService, requestFactory, DefaultVariableName.SMS_GRANT_TYPE);
        this.authenticationManager = authenticationManager;
        this.mobileParameter = ObjectUtils.isEmpty(mobileParameter) ? this.mobileParameter : mobileParameter;
        this.smsCodeParameter = ObjectUtils.isEmpty(smsCodeParameter) ? this.smsCodeParameter : smsCodeParameter;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

        Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
        String mobile = parameters.get(mobileParameter);
        String validate = parameters.get(smsCodeParameter);

        Authentication userAuth = new ExtendAuthenticationToken(mobile, validate, DefaultVariableName.SMS_GRANT_TYPE);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        try {
            userAuth = authenticationManager.authenticate(userAuth);
        } catch (AccountStatusException | BadCredentialsException ase) {
            throw new InvalidGrantException(ase.getMessage());
        }
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate user: " + mobile);
        }

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }

}
